<!--
 * @Author: chengjiang
 * @Date: 2024-06-08 17:38:52
 * @Description: 客户端数据展示
-->

<template>
  <div>
    <HeaderPage :logoQRcode="qrcode" />
    <div class="windowheight">
      <!-- 轮播图处理：大屏使用大图，手机屏幕使用轮播图 -->
      <!-- <div>
            <el-carousel :interval="3000" motion-blur>
                <el-carousel-item v-for="item in bannerList" :key="item.id">
                    <img v-if="item.id === 1" src="@/assets/b1.jpg" alt=""/>
                    <img v-if="item.id === 2" src="@/assets/b2.jpg" alt=""/>
                    <img v-if="item.id === 3" src="@/assets/b3.jpg" alt=""/>
                    <img v-if="item.id === 4" src="@/assets/b4.jpg" alt=""/>
                </el-carousel-item>
            </el-carousel>
        </div> -->
        <!-- 这里怎么加本地缓存 -->
      <img :src="backgroundImage" alt="" />
      <div class="text-center mt-2 grid grid-cols-1 gap-2">
        <div>
          <!-- header -->
          <div class="text-2xl text-[#c2a165] mb-1">-专业贵金属服务商-</div>
          <!-- 更新时间 -->
          <div class="text-base text-gray-400">更新时间：{{ updateTime }}</div>
        </div>
        <!-- 今日金价 -->
        <div class="goldsize font-900 text-[#b4873f]">
          今日金价：
          <span class="text-[#90281d] font-bold numsize mr-3">{{ todayGold }}</span>
          元/克
        </div>
        <!-- table数据 -->
        <table class="tabletextsize w-full table-auto text-center text-gray-800">
          <thead>
            <tr class="mt-2 mb-2">
              <th>商品</th>
              <th>回收</th>
              <th>销售</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="item in custGolds"
              :key="item.id"
              class="mt-1 mb-1 border-t font-bold text-black border-gray-300"
            >
              <td>{{ item.name }}</td>
              <td class="text-[#c2a165]">
                <span class="text-green-700" v-if="item.recycleStatus === 'down'">{{
                  num.has(item.name) ? item.recycle : item.recycle.toFixed(2)
                }}</span>
                <span class="text-red-700" v-else-if="item.recycleStatus === 'up'">{{
                  num.has(item.name) ? item.recycle : item.recycle.toFixed(2)
                }}</span>
                <span v-else>{{
                  num.has(item.name) ? item.recycle : item.recycle.toFixed(2)
                }}</span>
              </td>
              <td class="text-[#c2a165]">
                <span class="text-green-700" v-if="item.recycleStatus === 'down'">
                  {{ num.has(item.name) ? item.sale : item.sale.toFixed(2) }}</span
                >
                <span class="text-red-700" v-else-if="item.recycleStatus === 'up'">
                  {{ num.has(item.name) ? item.sale : item.sale.toFixed(2) }}</span
                >
                <span v-else> {{ num.has(item.name) ? item.sale : item.sale.toFixed(2) }}</span>
              </td>
            </tr>
          </tbody>
        </table>
        <!-- 提示 -->
        <div class="text-gray-400">每日今日金价仅供参考，实际以门店公示为准</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import HeaderPage from '_c/HeaderPage.vue'
import { defineComponent, ref } from 'vue'
import { useFooterInfoStore } from '@/stores/modules/footerInfo'
import { useGoldInfoStore } from '@/stores/modules/goldInfo'
const goldStore = useGoldInfoStore()
// goldStore.connectSocket()
// goldStore.freshListener()
goldStore.goldMap = new Map<string, GoldInfo>()
goldStore.setGoldInfoMap()
// import {useCustomerInfoStore} from '@/stores/modules/customergold'
import { getCustGoldInfo, ListGoldSetting, type Custgold, type GoldInfo } from '@/api/gold'
import { ListTitle } from '@/api/footer'
import { GetPhoto } from '@/api/home'

// 获取数据列表：initFunc
const infoMap = new Map<string, string>()
const potoMap = new Map<number, string>()
const qrcode = ref('')
const store = useFooterInfoStore()
const initFunc = async () => {
  await ListTitle(1, { priceType: 1 })
    .then((res) => {
      const lst = res.data
      for (const val of lst) {
        infoMap.set(val.name, val.description)
      }
      store.change(
        '',
        ('盘庚金热线：' + infoMap.get('盘庚金热线')) as string,
        ('业务：' + infoMap.get('电话')) as string,
        infoMap.get('地址') as string,
        ('备案：' + infoMap.get('备案')) as string,
        ''
      )
    })
    .catch(() => {})
  // 图片获取：
  await GetPhoto({ priceType: 1 })
    .then((res) => {
      const lst = res.data
      for (const val of lst) {
        potoMap.set(val.type, val.content)
      }
      store.changeVxCode(potoMap.get(2) as string)
      qrcode.value = potoMap.get(1) as string
      // console.log('通过管理系统获取的图片：', potoMap)
    })
    .catch((er) => {
      console.log('图片获取失败：', er)
    })
}
var lst: Array<any> = []
for (let i = 1; i <= 4; i++) {
  lst.push({
    id: i,
    img: new URL('../assets/b' + i + '.jpg', import.meta.url)
  })
}
const bannerList = ref(lst)
const updateTime = ref('2024-06-06 19:28:27')
type MoneyChangeStatus = 'up' | 'down' | 'none'
type Gold = {
  id: number
  name: string
  recycle: number
  recycleStatus: MoneyChangeStatus
  sale: number
  saleStatus: MoneyChangeStatus
}
const sortName: string[] = ['黄金', '白银', 'Au750', '铂金', '钯金']
const sortEnName: string[] = ['gold', 'internalSilver', 'Au750', 'internalBo', 'internalBa']
const custGolds = ref([] as Gold[])
const custGoldMap = ref(new Map<string, Gold>())
const todayGold = ref(0)
const timer = null as any
// 背景图片相关
const backgroundImage = ref('/bg1.jpg')
const IMAGE_CACHE_KEY = 'customer_bg_image'

// 取整的名字集合
let num = new Set<string>()
num.add('黄金')
num.add('铂金')
num.add('钯金')
num.add('Au750')
const backGoldMap = ref(new Map<string, GoldInfo>())

const tempMap = new Map<string, Gold>()

// 检查是否有缓存的图片
const checkCachedImage = () => {
  const cachedImage = localStorage.getItem(IMAGE_CACHE_KEY)
  const cacheTime = localStorage.getItem(`${IMAGE_CACHE_KEY}_time`)
  
  if (cachedImage && cacheTime) {
    const now = new Date().getTime()
    const cacheAge = now - parseInt(cacheTime)
    // 缓存有效期为1小时
    if (cacheAge < 60 * 60 * 1000) {
      // 创建一个Blob URL
      try {
        const byteString = atob(cachedImage.split(',')[1])
        const mimeString = cachedImage.split(',')[0].split(':')[1].split(';')[0]
        const ab = new ArrayBuffer(byteString.length)
        const ia = new Uint8Array(ab)
        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i)
        }
        const blob = new Blob([ab], { type: mimeString })
        backgroundImage.value = URL.createObjectURL(blob)
        return true
      } catch (e) {
        console.error('解析缓存图片失败:', e)
        // 清除无效缓存
        localStorage.removeItem(IMAGE_CACHE_KEY)
        localStorage.removeItem(`${IMAGE_CACHE_KEY}_time`)
      }
    } else {
      // 缓存过期，清除
      localStorage.removeItem(IMAGE_CACHE_KEY)
      localStorage.removeItem(`${IMAGE_CACHE_KEY}_time`)
    }
  }
  return false
}

// 缓存图片
const cacheImage = (imageUrl: string) => {
  // 如果已有缓存且未过期，则不重新缓存
  if (checkCachedImage()) {
    return
  }
  
  // 获取图片并缓存
  fetch(imageUrl)
    .then(response => response.blob())
    .then(blob => {
      const reader = new FileReader()
      reader.onload = () => {
        const dataUrl = reader.result as string
        localStorage.setItem(IMAGE_CACHE_KEY, dataUrl)
        localStorage.setItem(`${IMAGE_CACHE_KEY}_time`, new Date().getTime().toString())
      }
      reader.readAsDataURL(blob)
    })
    .catch(err => {
      console.error('缓存图片失败:', err)
    })
}

const getsocketMap = function () {
  tempMap.clear()
  let resMap = tempMap
  let goldMap = goldStore.goldMap
  const internalGold = goldMap.get('国际金')
  const internalSilver = goldMap.get('国际银')
  const internalBo = goldMap.get('国际铂')
  const internalBa = goldMap.get('国际钯')
  const gold = goldMap.get('黄金')
  resMap.set('黄金', {
    id: 1,
    name: '黄金',
    recycle:
      (internalGold?.Buy! < gold?.Buy! && internalGold?.Buy! != 0
        ? internalGold?.Buy!
        : gold?.Buy!) - 10,
    recycleStatus: 'none',
    saleStatus: 'none',
    sale: (internalGold?.Sell! > gold?.Sell! ? internalGold?.Sell! : gold?.Sell!) + 2 + 5
  })
  resMap.set('白银', {
    id: 2,
    name: '白银',
    recycle: internalSilver?.Buy! - 1.5,
    recycleStatus: 'none',
    saleStatus: 'none',
    sale: internalSilver?.Sell! + 2
  })
  resMap.set('Au750', {
    id: 3,
    name: 'Au750',
    recycle:
      ((internalGold?.Buy! < gold?.Buy! && internalGold?.Buy! != 0
        ? internalGold?.Buy!
        : gold?.Buy!) -
        10) *
      0.735,
    recycleStatus: 'none',
    saleStatus: 'none',
    sale: ((internalGold?.Sell! > gold?.Sell! ? internalGold?.Sell! : gold?.Sell!) + 2 + 5) * 0.755
  })
  resMap.set('铂金', {
    id: 4,
    name: '铂金',
    recycle: internalBo?.Buy! - 12,
    recycleStatus: 'none',
    saleStatus: 'none',
    sale: internalBo?.Sell! + 5
  })
  resMap.set('钯金', {
    id: 5,
    name: '钯金',
    recycle: internalBa?.Buy! - 16,
    recycleStatus: 'none',
    saleStatus: 'none',
    sale: internalBa?.Sell! + 5
  })
  return resMap
}
export default defineComponent({
  setup() {
    custGoldMap.value = getsocketMap()
    return {
      bannerList,
      updateTime,
      custGolds,
      todayGold,
      custGoldMap,
      num,
      qrcode,
      backGoldMap,
      timer,
      getsocketMap,
      backgroundImage, // 暴露背景图片响应式变量
      checkCachedImage, // 暴露检查缓存的方法
      cacheImage       // 暴露缓存图片的方法
    }
  },
  async created() {
    // 检查是否有缓存的背景图片
    checkCachedImage()
    
    // 缓存当前背景图片
    cacheImage('/bg1.jpg')
    this.getsocketData()
    await initFunc()
    this.getProjectList().then(() => {
      // goldStore.goldMap = new Map<string, GoldInfo>()
      goldStore.setGoldInfoMap()
      // this.custGoldMap = this.getsocketMap()
      this.getCurrentTime()
      //
      this.timer = setInterval(() => {
        goldStore.setGoldInfoMap()
        this.getProjectList().then(() => {
          this.getsocketData()
          // 如果价格超过两块再次更新时间
          // this.getHttpData()
          this.getCurrentTime()
        })
      }, 1000)
    })
  },
  beforeUnmount() {
    clearInterval(this.timer)
    this.timer = null
    // goldStore.disconnect()
  },
  methods: {
    // 向上取整的函数
    ceil(num: number) {
      return Math.ceil(num)
    },
    // 向下取整的函数
    floor(num: number) {
      return Math.floor(num)
    },
    getsocketData() {
      // 和上一次对比黄金价格，
      let curMap = this.getsocketMap()
      this.custGolds.length = 0
      for (let i = 0; i < sortName.length; i++) {
        const name = sortName[i]
        const enName = sortEnName[i]
        const gold = curMap.get(name)
        const preGold = this.custGoldMap.get(name)
        const threshold = 0.2 // 设置比较阈值变量
        if (gold && preGold) {
          let recyccle =
            Math.abs(gold.recycle - preGold.recycle) > threshold ? gold.recycle : preGold.recycle
          let sale = Math.abs(gold.sale - preGold.sale) > threshold ? gold.sale : preGold.sale
          if (num.has(name)) {
            recyccle = this.floor(recyccle)
            sale = this.ceil(sale)
          }
          recyccle += this.backGoldMap.get(enName)?.Buy ? this.backGoldMap.get(enName)?.Buy! : 0
          sale += this.backGoldMap.get(enName)?.Sell ? this.backGoldMap.get(enName)?.Sell! : 0
          if (recyccle < 0) {
            recyccle = 0
          }
          if (sale < 0) {
            sale = 0
          }
          let recycleStatus: MoneyChangeStatus = 'none'
          if (gold.recycle - preGold.recycle > threshold) {
            recycleStatus = 'up'
          } else if (gold.recycle - preGold.recycle < -threshold) {
            recycleStatus = 'down'
          }
          let saleStatus: MoneyChangeStatus = 'none'
          if (gold.sale - preGold.sale > threshold) {
            saleStatus = 'up'
          } else if (gold.sale - preGold.sale < -threshold) {
            saleStatus = 'down'
          }
          if (name === '黄金') {
            this.todayGold = this.ceil(sale!)
          }
          if (sale === undefined || recyccle === undefined) {
            console.log(' undefined')
            return
          }
          this.custGolds.push({
            id: i + 1,
            name: name,
            recycle: recyccle,
            sale: sale,
            recycleStatus: recycleStatus,
            saleStatus: saleStatus
          })
        }
      }
      // return this.custGolds
    },
    // updateTime: 每秒获取当前系统时间并刷新。
    getCurrentTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      //
      this.custGoldMap = this.getsocketMap()
      this.updateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    handleToGoldPageClick() {
      this.$router.push('/gold').then(() => {
        this.$router.go(0)
      })
    },
    getWindowWith_MAX() {
      const windowWidth =
        window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
      return windowWidth <= 612
    },
    // 获取金价调整。
    async getBackGoldChange(): Promise<Map<string, GoldInfo>> {
      let ret = new Map<string, GoldInfo>()
      await ListGoldSetting({ priceType: 1 })
        .then((res) => {
          const lst = res.data
          for (const val of lst) {
            ret.set(val.currencyCode, {
              Buy: val.recyclePrice / 100,
              C: val.currencyCode,
              H: 0,
              L: 0,
              MaxMni: {
                H: 0,
                L: 0
              },
              Sell: val.sellPrice / 100,
              name: val.currencyName
            })
          }
        })
        .catch((err) => {
          console.error('getBackGoldChange 请求接口失败:', err)
        })

      return ret
    },
    async getProjectList() {
      this.backGoldMap = new Map()
      try {
        await this.getBackGoldChange().then((ret) => {
          if (ret) {
            this.backGoldMap = new Map(ret)
          }
        })
      } catch (error) {
        console.error('getBackGoldChange 请求接口失败:', error)
        // 刷新页面
        // window.location.reload()
      }
    }
  }
})
</script>

<style>
@media (max-width: 1024px) {
  .goldsize {
    font-size: 1.5rem;
  }

  .numsize {
    font-size: 3.5rem;
  }

  .tabletextsize {
    font-size: 1.5rem;
    line-height: 3rem;
  }

  .el-carousel__container {
    height: 170px;
  }
}

@media (min-width: 1024px) {
  .goldsize {
    font-size: 5rem;
  }

  .numsize {
    font-size: 8rem;
  }

  .tabletextsize {
    font-size: 2rem;
    line-height: 4rem;
  }

  .el-carousel__container img {
    size: 350px !important;
  }

  .el-carousel__container {
    height: 200px;
  }
}

.el-carousel__container img {
  margin: auto;
}

html,
body,
#app {
  background-color: #fefefe;
}

.windowheight {
  display: flex;
  flex-direction: column;
  height: 75vh;
  /* 视口高度 */
}
</style>
